﻿using System;
using System.Collections.Generic;
using System.Runtime.Serialization;

namespace StringExt {

    [Serializable]
    public class PatternException : Exception {

        public PatternException() {
        }

        public PatternException(string message)
            : base(message) {
        }

        public PatternException(string message, Exception inner)
            : base(message, inner) {
        }

        protected PatternException(
            SerializationInfo info,
            StreamingContext context)
            : base(info, context) {
        }
    }

    public static class StringExt {

        private static readonly char[] TokenSep = { ';' };
        private static readonly char[] PairSep = { '=' };

        public enum RemoveSurroundingBlanks {
            Yes,
            No
        }

        public static IDictionary<string, string> ToDictionary(this string strToConvert, RemoveSurroundingBlanks removeSurroundingBlanks) {

            IDictionary<string, string> dict = new Dictionary<string, string>();

            if (String.IsNullOrEmpty(strToConvert)) {
                return dict;
            }

            string[] token = SplitInToken(strToConvert);
            foreach (string s in token) {
                string[] pair = SplitInPair(s, removeSurroundingBlanks);
                dict.Add(pair[0], pair[1]);
            }
            return dict;
        }

        internal static string[] SplitInToken(string strToConvert) {
            string[] token = strToConvert.Split(TokenSep, StringSplitOptions.RemoveEmptyEntries);
            return token;
        }

        internal static string[] SplitInPair(string strToConvert, RemoveSurroundingBlanks removeSurroundingBlanks) {

            string[] pair = strToConvert.Split(PairSep, StringSplitOptions.RemoveEmptyEntries);

            char[] doublePairSepChar = {PairSep[0], PairSep[0]};
            string doublePairSep = new string(doublePairSepChar);

            if (pair.Length != 2 || strToConvert.IndexOf(doublePairSep) > 0) {
                throw new PatternException(DictionaryExtResource.PatternException);
            }

            if (RemoveSurroundingBlanks.Yes == removeSurroundingBlanks) {
                RemoveBlanksFromPair(pair);
            }

            return pair;
        }

        private static void RemoveBlanksFromPair(string[] pair) {
            pair[0] = pair[0].Trim();
            pair[1] = pair[1].Trim();
        }
    }
}


